//
//  SRClassHomeWorkDetailViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/7/20.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRClassHomeWorkDetailViewController.h"

#import "SRWorkListItemModel.h"
#import "SRHomeworkFinishTableViewCell.h"
#import <MJRefresh/MJRefresh.h>
#import "SRSchoolClassServices.h"
#import "SRWorkDetailViewController.h"

#import "SRCommentHomeworkViewController.h"
#import "SRHomeworkFinishHeaderView.h"
#import "SRBookCatalogueSectionHeaderView.h"
#import "SRClassHomeworkStudentFinishViewController.h"

#import "SRHomewokPictureViewController.h"
#import "SRHomeworkAudioViewController.h"
#import "SRHomewokRecordViewController.h"

@interface SRClassHomeWorkDetailViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) SRHomeworkFinishHeaderView *headerView;
@property (strong, nonatomic) UIButton *rightButton;

@property (strong, nonatomic) NSMutableArray *items;
@property (assign, nonatomic) NSInteger pageIndex;

@end

@implementation SRClassHomeWorkDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
    
    self.title = @"任务详情";
    [self setupData];
    [self setupView];
    [self setupNavigationItem];
    
    if (self.userType == SRSchoolClassUserTypeTeacher) {
        self.rightButton.hidden = NO;
    } else {
        self.rightButton.hidden = YES;
    }
    
    [self showLoadingViewWithCompletedBlock:nil];
    [self queryData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 125);
    self.tableView.tableHeaderView = self.headerView;
}

#pragma mark - setup

- (void)setupData {
    self.pageIndex = 0;
    self.items = [@[] mutableCopy];
}

- (void)setupView {
    
    WEAKSELF
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 115;
    
    [self.tableView registerNib:[UINib nibWithNibName:kSRHomeworkFinishTableViewCell bundle:nil] forCellReuseIdentifier:kSRHomeworkFinishTableViewCell];
    [self.tableView registerClass:[SRBookCatalogueSectionHeaderView class] forHeaderFooterViewReuseIdentifier:kSRBookCatalogueSectionHeaderView];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.top.equalTo(self.view);
    }];
    self.view.backgroundColor = self.tableView.backgroundColor = css.color_2;
    
    
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        weakSelf.pageIndex = 0;
        [weakSelf queryData];
    }];
    
//    [self.tableView addLegendFooterWithRefreshingBlock:^{
//        [weakSelf queryData];
//    }];
    
    self.headerView = [[[NSBundle mainBundle] loadNibNamed:@"SRHomeworkFinishHeaderView" owner:nil options:nil] firstObject];
    self.headerView.userType = SRSchoolClassUserTypeTeacher;
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 125);
    self.tableView.tableHeaderView = self.headerView;
    [self.headerView updateCellInfo:self.detailModel];
    
}


- (void)setupNavigationItem {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 65, 40);
    [rightButton setTitle:@"催作业" forState:UIControlStateNormal];
    rightButton.titleLabel.font = css.fontOfH5;
    
    self.rightButton = rightButton;
    [rightButton addTarget:self action:@selector(onRightButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    [self setRightBarButtonItem:rightItem];
}
#pragma mark - Query Data

- (void)onRightButton:(id)sender {
    WEAKSELF
    UIAlertView *alertView = [UIAlertView alertViewWithTitle:@"作业提醒" message:@"快去完成练习哦" cancelButtonTitle:@"取消" didDismissBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            [weakSelf taskRemind];
        }
        
    } otherButtonTitles:@"确定", nil];
    [alertView show];
}

- (void)taskRemind {
//    WEAKSELF
    [SRSchoolClassServices TaskRemindGroupID:self.detailModel.group_id taskID:self.detailModel.task_id successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
       
    } failureBlock:^(id responseObject, NSError *error) {
        
    }];
}

- (void)queryData{
    WEAKSELF
    
    [SRSchoolClassServices queryTaskFinishListGroupID:self.detailModel.group_id taskID:self.detailModel.task_id type:self.homeworkType successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf hideLoadingView];
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];

        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {

            NSArray *addItems = @[];
            if ([responseDataObject isKindOfClass:[NSArray class]]) {
                addItems = responseDataObject;
            }

            if (weakSelf.pageIndex == 0) {
                [weakSelf.items removeAllObjects];
            }

            if ([addItems count] <= 0) {
                    //没有更多
                [weakSelf.tableView.footer noticeNoMoreData];
//                if (weakSelf.pageIndex == 0) {
//                    [weakSelf emptyLoadingViewWithTitle:nil];
//                }

            } else {
                weakSelf.pageIndex += [addItems count];
                [weakSelf.items addObjectsFromArray:addItems];
            }

            [weakSelf.tableView reloadData];

        } else {
//            if (weakSelf.pageIndex == 0) {
//                [weakSelf failedLoadingViewWithTitle:nil];
//            }
        }

    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf.tableView.header endRefreshing];

        [weakSelf.tableView.footer endRefreshing];

//        if ([weakSelf.items count] <= 0) {
//            [weakSelf failedLoadingViewWithTitle:nil];
//        }

    }];
    
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SRHomeworkFinishTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kSRHomeworkFinishTableViewCell forIndexPath:indexPath];
    cell.userType = self.userType;
    
    SRWorkListItemModel *item = self.items[indexPath.row];
    [cell updateCellInfo:item];
    WEAKSELF
    cell.touchDoHomeworkButtonBlock = ^(SRWorkListItemModel *item) {
        [weakSelf showCommentVCForItem:item];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 45;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        SRBookCatalogueSectionHeaderView *sectionHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kSRBookCatalogueSectionHeaderView];
        sectionHeaderView.leftViewHidden = YES;
        
        sectionHeaderView.titleLabel.text = [NSString stringWithFormat:@"已完成学员（%lu）", (unsigned long)[self.detailModel.cur_num integerValue]];
    
        return sectionHeaderView;
}

#pragma mark - UITableViewDelegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SRWorkListItemModel *item = self.items[indexPath.row];
    item.ctype = self.homeworkType;
    
    if (item.ctype == SRClassHomeworkTypeDubbing) {
        SRWorkDetailViewController *vc = [[SRWorkDetailViewController alloc] init];
        vc.show_id = item.show_id;
        vc.listItemModel = item;
        
        [self.navigationController pushViewController:vc animated:YES];
    } else if (item.ctype == SRClassHomeworkTypeAudio){
        SRHomeworkAudioViewController *vc = [[SRHomeworkAudioViewController alloc] init];
        vc.taskID = item.finish_id;
        vc.homeworkType = SRClassHomeworkTypeAudio;
        vc.isFinishedDetail = YES;
        [self.navigationController pushViewController:vc animated:YES];
    } else if (item.ctype == SRClassHomeworkTypePicture){
        SRHomewokPictureViewController *vc = [[SRHomewokPictureViewController alloc] init];
        vc.taskID = item.finish_id;
        vc.homeworkType = SRClassHomeworkTypePicture;
        vc.isFinishedDetail = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (item.ctype == SRClassHomeworkTypeRecord){
        SRHomewokRecordViewController *vc = [[SRHomewokRecordViewController alloc] initWithNibName:@"SRHomewokRecordViewController" bundle:nil];
        vc.taskID = item.finish_id;
//        vc.homeworkType = SRClassHomeworkTypePicture;
        vc.isFinishedDetail = YES;
        
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
}


- (void)showCommentVCForItem:(SRWorkListItemModel *)item {
    WEAKSELF
    
    if (item.comment && [item.comment length] > 0) {
            //已经点评的，去查看点评
        SRClassHomeworkStudentFinishViewController *vc = [[SRClassHomeworkStudentFinishViewController alloc] init];
        vc.detailModel = item;
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }

    SRCommentHomeworkViewController *vc = [[SRCommentHomeworkViewController alloc] init];
    vc.maxInputTextCount = 800;
    vc.minInputTextCount = 2;
    vc.tipTitle = @"作业点评";
    vc.isHomeworkComment = YES;
    vc.showID = item.show_id;
    vc.homeworkType = self.homeworkType;
    vc.problem_finish_id = item.finish_id;
    
    vc.didChangeInputTextBlock = ^(NSString *inputText) {
//        weakSelf.nickname = inputText;
//        [SRLoginUser setNickname:inputText];
//        [weakSelf updateCellDataWithID:userinfo_nickname value:inputText];
        
    };
    
    vc.didSendBlock = ^(NSString *inputText) {
        weakSelf.pageIndex = 0;
        [weakSelf queryData];
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}


@end
